<template>
  <div v-if="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="基础信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="8">
                <px-form-item label="设备名称" prop="eqpName">
                  <px-input v-model="formValue.eqpName" placeholder="请输入" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备编号" prop="eqpCode">
                  <px-input v-model="formValue.eqpCode" placeholder="请输入" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备编码" prop="eqpId">
                  <px-input v-model="formValue.eqpId" placeholder="请输入出库单号" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备类型" prop="typeName">
                  <px-input :value="formValue.typeName" maxlength="50" clearable disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="地块" prop="facCode">
                  <px-select v-model="formValue.facCode" placeholder="请选择" clearable>
                    <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="安装位置" prop="positionCode">
                  <px-cascader
                    ref="treeSelectRef"
                    v-model="formValue.positionCode"
                    placeholder="请先选择地块"
                    :disabled="!formValue.facCode"
                    :options="positionCodeList"
                    :props="{
                      children: 'children',
                      label: 'name',
                      value: 'code',
                      checkStrictly: true
                    }"
                    :show-all-levels="false"
                    clearable
                    @focus="selectPositionCode"
                    @change="handleCascaderChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="品牌" prop="brand">
                  <px-input v-model="formValue.brand" placeholder="请输入" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="规格型号" prop="specification">
                  <px-input v-model="formValue.specification" placeholder="请输入" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="联系人" prop="contactName">
                  <px-select-v2
                    v-model="formValue.contactName"
                    filterable
                    clearable
                    :options="contactNameList"
                    placeholder="请选择"
                    @change="contactNameChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="联系电话" prop="contactTel">
                  <px-input v-model="formValue.contactTel" placeholder="请先选择联系人" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="合同PO编号" prop="htCode">
                  <px-input v-model="formValue.htCode" placeholder="请输入" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="合同PO名称" prop="htName">
                  <px-input v-model="formValue.htName" placeholder="请输入" maxlength="50" />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="使用信息" class="useInfo">
        <template v-slot:content>
          <div class="img">
            <div class="imgBox" />
            <div class="imgSize">设备图纸</div>
          </div>
          <PhotoUpload
            v-if="!isMain && !isView"
            :photoType="photoType"
            :photoData="{ moduleName: moduleName }"
            :photoList="formValue.pictureLists"
            :countLimit="10"
            style="margin-bottom: 18px"
            @changePhotoList="changePhotoList"
            @savePhotoStatus="savePhotoStatus"
          />
          <div class="img">
            <div class="imgBox" />
            <div class="imgSize">关联文档</div>
          </div>
          <FileUpload
            v-if="!isMain && !isView"
            :fileType="fileType"
            :fileData="{ moduleName: moduleName }"
            :fileList="formValue.docLists"
            style="margin-bottom: 18px"
            @changeFileList="changeFileList"
            @saveFileStatus="saveFileStatus"
          />
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="关联备品备件">
        <template v-slot:content>
          <px-button style="margin-bottom: 8px" type="primary" @click="dialogVisibleShow">关联备件</px-button>
          <px-table :data="formValue.tableData" class="equip-table" size="small" height="280" border>
            <px-table-column type="index" label="序号" min-width="60" align="center" fixed="left" show-overflow-tooltip />
            <px-table-column fixed="left" prop="facCodeDesc" label="归属地块" min-width="160" show-overflow-tooltip />
            <px-table-column prop="sparePartName" label="备件名称" min-width="160" show-overflow-tooltip />
            <px-table-column prop="specification" label="规格型号" min-width="160" show-overflow-tooltip />
            <px-table-column prop="eqpTypeCodeDesc" label="备件类型" min-width="160" show-overflow-tooltip />
            <px-table-column prop="sparePartUnit" label="单位" min-width="160" show-overflow-tooltip />
            <px-table-column prop="currentStock" label="数量" min-width="160" show-overflow-tooltip />
            <px-table-column fixed="right" label="操作" min-width="144" align="center">
              <template #default="scope">
                <px-button link type="danger" @click="handleDelete(scope.$index)">
                  <px-icon>
                    <Delete />
                  </px-icon>
                </px-button>
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button :disabled="photoStatusFlag || fileStatusFlag" type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
  <!-- 选择备件弹窗 -->
  <AddTypeDialog :visible="dialogVisible" :eqpTypeCode="eqpTypeCode" @closeDialog="closeDialog" @addTableRow="addTableRow" />
</template>
<script setup lang="ts">
import { ref, reactive, toRefs, watch, computed, onMounted } from "vue";
import { PxMessage } from "px-ui";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import AddTypeDialog from "./AddTypeDialog.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { addToolLedger, viewToolLedger, editToolLedger, getEqpId } from "@/api/erc/equip";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
const treeSelectRef = ref<any>(null);

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "tableType", "sparePartsId", "username", "treeNameType", "typeCode", "typeName", "treeTypeid"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  moduleName: "ERC_LEDGER",
  formValue: {
    id: "",
    eqpId: "",
    eqpName: "",
    facCode: "",
    facName: "",
    specification: "",
    brand: "",
    contactId: "",
    typeName: "",
    typeCode: "",
    positionCode: "",
    contactTel: "",
    pictureLists: [], //图片
    docLists: [], //文档
    tableData: [],
    generatedNumbers: []
  },
  eqpTypeCode: "", //传给子组件的编码
  typeCodeList: [], //设备类型
  facCodeList: [], //地块
  positionCodeList: [], //位置信息
  contactNameList: [], //联系人
  selectDialogVisible: false,
  dialogVisible: false,
  photoType: "add",
  fileType: "add",
  photoStatusFlag: false,
  fileStatusFlag: false,
  defaultExpandedKeys: []
});
const {
  photoType,
  moduleName,
  fileType,
  formValue,
  eqpTypeCode,
  facCodeList,
  contactNameList,
  positionCodeList,
  dialogVisible,
  photoStatusFlag,
  fileStatusFlag,
  defaultExpandedKeys
} = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  eqpName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
  // eqpCode: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
  eqpId: [{ required: true, message: "设备编码不能为空", trigger: "blur" }],
  facCode: [{ required: true, message: "地块不能为空", trigger: "change" }],
  positionCode: [{ required: true, message: "安装位置不能为空", trigger: "change" }]
}));
//获取设备编码信息
const getEqpIdList = async () => {
  const data = await getEqpId();
  formValue.value.eqpId = data;
};
//位置下拉框
const selectPositionCode = () => {
  positionLedger({ facCode: formValue.value.facCode }).then(res => {
    positionCodeList.value = res;
  });
  defaultExpandedKeys.value = positionCodeList.value.map(node => node.name);
};
const handleCascaderChange = pathValues => {
  if (!pathValues || pathValues.length === 0) return;
  // 判断选中层级（路径长度即为层级）
  const level = pathValues.length;
  if (level <= 2) {
    // 前两级节点：重置选中值，保持下拉框展开
    formValue.value.positionCode = [];
    treeSelectRef.value?.togglePopperVisible(true); // 保持展开状态
  } else {
    // 第三级及以下：保留选中值（自动回显）
    formValue.value.positionCode = pathValues.slice(-1)[0].toString();
  }
};
//基础信息
import { positionLedger } from "@/api/erc/equip";
// 地块下拉框
import { queryDictData } from "@/api/common";
const queryfacCodeList = async () => {
  facCodeList.value = [];
  const params = {
    typeCode: "ERC_FACTORY_AREA"
  };
  const data = await queryDictData(params);
  facCodeList.value = data;
};
//联系人下拉,获取contactName
const queryRecipientIdSelect = async () => {
  contactNameList.value = await getEmployeeIdAndName(["HSE"], 0);
};
// 电话联动
const contactNameChange = val => {
  const arr = contactNameList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.contactName = arr[0].label;
    formValue.value.contactTel = arr[0].phone;
  }
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    queryfacCodeList();
    queryRecipientIdSelect();
    selectPositionCode();
    formValue.value.typeName = props.typeName;
    if (props.tableType === "add") {
      getEqpIdList();
      formValue.value.eqpName = props.typeName;
      formValue.value.typeCode = props.typeCode;
      photoType.value = "add";
      fileType.value = "add";
    } else if (props.tableType === "edit") {
      photoType.value = "edit";
      fileType.value = "edit";
      formValue.value = JSON.parse(JSON.stringify(props.sparePartsId));
      formValue.value.facCode = props.sparePartsId.facCode;
      formValue.value.typeCode = props.sparePartsId.typeCode;
      formValue.value.pictureLists = props.sparePartsId.pictureList || [];
      formValue.value.docLists = props.sparePartsId.docList || [];
      formValue.value.tableData = props.sparePartsId.sparePartIdList || [];
      queryTable();
    } else if (props.tableType === "view") {
      photoType.value = "view";
      fileType.value = "view";
    }
  } else {
    formValue.value = {
      eqpId: "",
      contactId: null,
      eqpName: "",
      facName: "",
      facCode: "",
      specification: "",
      brand: "",
      typeCode: "",
      positionCode: "",
      contactName: "",
      contactTel: "",
      pictureLists: [],
      docLists: [],
      tableData: []
    };
  }
});
// 删除表格某一行
const handleDelete = (index: any) => {
  formValue.value.tableData.splice(index, 1);
};
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 选择备件后添加表格数据
const addTableRow = val => {
  if (val && val.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.id);
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.id)) {
        arr2.push(item);
      }
    });
    formValue.value.tableData = [...arr2, ...formValue.value.tableData];
  }
};
// 新的图片列表
const changePhotoList = val => {
  formValue.value.pictureLists = val;
};
// 新的文件列表
const changeFileList = val => {
  formValue.value.docLists = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};
//关联备件回显
const queryTable = async () => {
  const params = {
    eqpId: props.sparePartsId.eqpId
  };
  const data = await viewToolLedger(params);
  formValue.value.tableData = data;
};

// 提交
const handleSubmit = useThrottleFn(async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      //图片
      formValue.value.pictureList = [];
      if (formValue.value.pictureLists && formValue.value.pictureLists.length > 0) {
        formValue.value.pictureLists.forEach(item => {
          if (item?.id) {
            formValue.value.pictureList.push(item.id);
          } else if (item?.response.data.id) {
            formValue.value.pictureList.push(item.response.data.id);
          }
        });
      }
      //文档
      formValue.value.docList = [];
      if (formValue.value.docLists && formValue.value.docLists.length > 0) {
        formValue.value.docLists.forEach(item => {
          if (item?.id) {
            formValue.value.docList.push(item.id);
          } else if (item?.response.data.id) {
            formValue.value.docList.push(item.response.data.id);
          }
        });
      }
      // 备件
      formValue.value.sparePartIdList = [];
      if (formValue.value.tableData && formValue.value.tableData.length > 0) {
        formValue.value.tableData.forEach(item => {
          if (item?.id) {
            formValue.value.sparePartIdList.push(item.id);
          } else if (item?.response.data.id) {
            formValue.value.sparePartIdList.push(item.response.data.id);
          }
        });
      }
      if (props.tableType === "add") {
        const params = { ...formValue.value, typeCode: props.typeCode };
        await addToolLedger(params);
        PxMessage.success("创建成功");
        emits("backMainPage");
        emits("queryTable");
      } else if (props.tableType === "edit") {
        const params = {
          ...formValue.value,
          id: props.sparePartsId.id
        };
        await editToolLedger(params);
        PxMessage.success("编辑成功");
        emits("backMainPage");
        emits("queryTable");
      }
    }
  });
}, delay);
//点击关联备件弹窗
const dialogVisibleShow = () => {
  dialogVisible.value = true;
  eqpTypeCode.value = formValue.value.typeCode;
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");

::v-deep .px-select-v2__placeholder {
  position: absolute;
  top: 50%;
  width: 401px;
  width: calc(100% - 52px);
  height: 32px;
  margin-inline-start: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transform: translateY(-50%);
}

.img {
  display: flex;
  align-items: center;
  width: 100%;

  /* 垂直居中 */
  height: 22px;

  /* 大盒子的高度 */
  margin-bottom: 8px;
  font-size: 14px;
}

.imgBox {
  width: 3px;
  height: 16px;
  margin-right: 9px;
  background: #3b82f6;
  border-radius: 0 100px 100px 0;
}

.imgSize {
  height: 22px;
  font-size: 14px;
  font-weight: 600;
  line-height: 22px;
  color: rgb(0 0 0 / 80%);
}

:deep(.px-cascader) {
  width: 100%;
}
</style>
